package com.itheima.demo2;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo2 {
    public static void main(String[] args){
        String regex="黑马";

        try {
            method1(regex);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void method1(String regex) throws IOException {
        int count = 0;
        BufferedReader br=new BufferedReader(new FileReader("D:\\APP\\IT\\code\\java-homework\\a.txt"));
        String line=null;
        while ((line=br.readLine())!=null){

            Pattern pattern=Pattern.compile(regex);
            Matcher matcher= pattern.matcher(line);
            while (matcher.find()){
                count++;
            }
        }
      //  System.out.println(count);
        br.close();
        method2(regex,count);

    }

    //---------
    public static void method2(String regex,int count) throws IOException {
        BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\APP\\IT\\code\\java-homework\\a.txt",true));
        bw.newLine();
        bw.write("关键字 "+regex+" 出现的次数为 "+count);
        bw.close();
    }

}
